package org.whuims.web.comment;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.whuims.entity.Comment;
import org.whuims.service.account.AccountService;
import org.whuims.service.account.ShiroDbRealm;
import org.whuims.service.comment.CommentService;
import org.whuims.service.news.InforService;

import java.util.Date;

/**
 * Created by Roger on 2016/12/21.
 */
@Controller
@RequestMapping("/cmt")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private InforService inforService;
    @Autowired
    private AccountService accountService;

    /**
     * ajax 请求提交回复
     *
     * @param comment
     * @param targetUid
     * @param inforId
     * @return
     */
    @RequestMapping(value = "/for/{inforId}", method = RequestMethod.POST)
    @ResponseBody
    public Comment create(Comment comment, Long targetUid, @PathVariable Long inforId) {
        comment.setAuthor(accountService.getUser(getCurrentUserId()));
        if (targetUid != null) {
            comment.setTargetUser(accountService.getUser(targetUid));
        }
        comment.setInfor(inforService.getInfor(inforId));
        comment.setPublishDate(new Date());
        commentService.save(comment);
        return comment;
    }


    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }
}
